package dao.daoimpl;

import dao.StudentDao;
import entity.Constants;
import entity.Pager;
import entity.Student;
import util.JdbcUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StudentDaoImpl implements StudentDao {
    @Override
    public Pager<Student> findStudent(Student model, int pageNum, int pageSize) {
        Pager<Student> result=null;
        List<Object> paramList = new ArrayList<Object>();  //查询参数list
        String stuName = model.getStuName();               //两个查询参数
        int gender = model.getGender();
        StringBuilder sql = new StringBuilder("select * from t_student where 1=1 ");
        StringBuilder countSql = new StringBuilder("select count(id) as recordTotal from t_student where 1=1 ");

        if(stuName!=null&&!stuName.equals("")){
            sql.append("and stu_name like ? ");
            countSql.append("and stu_name like ? ");
            paramList.add("%"+stuName+"%");
        }
        if(gender== Constants.GENDER_MALE||gender==Constants.GENDER_FEMALE){
            sql.append("and gender = ? " );
            countSql.append("and gender = ? ");
            paramList.add(gender);
        }
        int fromIndex = (pageNum-1)*pageSize;
        sql.append(" limit "+ fromIndex +","+ pageSize);


        JdbcUtil jdbcUtil = null;
        try {
            jdbcUtil = new JdbcUtil();
            jdbcUtil.getConnection();

            //取总记录数
            List<Map<String, Object>> totalList = jdbcUtil.findResult(countSql.toString(), paramList);
            Map<String, Object> totalMap = totalList.get(0);
            int recordTotal = ((Number)totalMap.get("recordTotal")).intValue();

            //取stuList
            List<Student> stuList = new ArrayList<Student>();
            List<Map<String, Object>> findStuResult = jdbcUtil.findResult(sql.toString(), paramList);
            for (Map<String, Object> map : findStuResult) {
                Student stu = new Student(map);
                stuList.add(stu);
            }
            int totalPage = recordTotal/pageSize;
            if(recordTotal%pageSize!=0){
                totalPage+=1;
            }
            result =new Pager<Student>(pageSize, pageNum, recordTotal, totalPage, stuList);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(jdbcUtil!=null)
                jdbcUtil.releaseConn();
        }
        return result;
    }
}
